package com.demo.demoproject.utils;

import com.demo.demoproject.constants.SecretKeysConstants;
import com.demo.demoproject.constants.TimeConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    /**
     * 生成JWT
     * @param uid 用户uid
     * @return 生成的JWT
     */
    @Nullable
    @Contract(pure = true)
    public static String generateJwt(String uid) {
        Map<String, Object> claims = new HashMap<>() {{
            put("uid", uid);
        }};

        return Jwts.builder()
                // 设置JWT的签名算法和签名使用的秘钥
                .signWith(SecretKeysConstants.SECRET_KEY_JWT)
                // 设置JWT的主题
                .claims(claims)
                // 设置JWT的过期时间
                .expiration(new Date(TimeConstants.MONTH + System.currentTimeMillis()))
                .compact();
    }

    /**
     * 解析JWT
     * @param token 需要解析的JWT
     * @return 解析后的JWT
     */
    @Nullable
    @Contract(pure = true)
    public static Claims parseJwt(String token) {
        // 得到DefaultJwtParser
        JwtParser jwtParser = Jwts.parser()
                // 设置签名的秘钥
                .verifyWith(SecretKeysConstants.SECRET_KEY_JWT)
                .build();
        Jws<Claims> jws = jwtParser.parseSignedClaims(token);
        return jws.getPayload();
    }
}
